#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <thread>

int main()
{
    /*Create socket*/
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        printf("Error : Create socket failed!\n");
        return -1;
    }

    while (true)
    {

        /*Connect to Server*/
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(50000);
        inet_pton(AF_INET, "192.168.1.216", &addr.sin_addr.s_addr);

        int ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
        if (ret == -1)
        {
            printf("Error : Connect failed!\n");
            std::this_thread::sleep_for(std::chrono::seconds(1)); // retry after 1s
            continue;
        }

        /*Communication*/
        while (true)
        {
            char buf[128];
            memset(buf, 0, 128);
            int len = read(fd, buf, sizeof(buf));
            if (len > 0)
            {
                printf("recv(%d Bytes):", len);
                for (int i = 0; i < len; i++)
                {
                    printf("0x%02X ", buf[i]);
                }
                printf("\n");
            }
            else if (len == 0)
            {
                printf("Disconnected!\n");
                break;
            }
            else
            {
                printf("Error : Read failed!\n");
                break;
            }
        }
        close(fd);
    }

    return 0;
}